package com.mti.utils;

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class StrUtils {

    /**
     * 将,转义为|
     * @param str
     * @return
     */
    public static String replaceKeyString(String str) {
        if (StringUtils.isNotBlank(str) && str.contains(",")) {
            return str.replace("，", "|");
        } else {
            return str;
        }
    }

    /**
     * 字符串转化为List数组
     * @param str
     * @return
     */
    public static <T> List<String> strToList(String str) {

        List<String> result =  new ArrayList<String>();

        if (StringUtils.isNotBlank(str)) {
            if(str.contains(",")) {
                String[] list = str.split(",");
                for (int i = list.length - 1; i >= 0; i--) {
                    if (list[i] != null && !"null".equalsIgnoreCase(list[i].trim())) {
                        result.add(list[i]);
                    }
                }
            }
        }

        return result;
    }

    /**
     * 字符串转化为数组
     * @param str
     * @return
     */
    public static Integer[] strToIntArr(String str) {
        if (StringUtils.isNotBlank(str)) {
            if(str.contains(",")){
                String[] strArr = str.split(",");
                int len = strArr.length;
                Integer[] arr = new Integer[len];
                for(int i=0; i<len; i++){
                    arr[i] = Integer.parseInt(strArr[i]);
                }
                return arr;
            } else {
                return new Integer[]{Integer.parseInt(str)};
            }
        } else {
            return new Integer[]{};
        }
    }

    /**
     * 根据身份证获取年龄
     * @param sfzh 身份证号码
     * @return 年龄
     */
    public static String getAgeBySfzh(String sfzh){
        if(StringUtils.isEmpty(sfzh))
            return "0";
        String birth = sfzh.substring(6,14);
        System.out.println("===>"+birth);
        LocalDate birthDate = LocalDate.parse(birth, DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate now = LocalDate.now();
        return now.getMonthValue()<birthDate.getMonthValue()?String.valueOf(now.getYear()-birthDate.getYear()-1):String.valueOf(now.getYear()-birthDate.getYear());
    }


    public static  String collectionToString(Collection<?> collection, String str){
        if(collection.size()==0) return null;
        StringBuilder sb = new StringBuilder();
        Iterator<?> it = collection.iterator();
        while (it.hasNext()){
            if(sb.length()>0) sb.append(str).append(it.next());
            else sb.append(it.next());
        }
        return sb.toString();
    }
}
